import { IS_DEV } from '@/library/tool-kits/get-process-env'
import { error } from '@/library/tool-kits/log'

export function measureCSSLength(raw: string | undefined | null): number {
  if (raw === null || raw === undefined || raw === '') {
    if (IS_DEV) {
      error(
        'Global',
        'Something went wrong when calculating CSS length.',
      )
    }
    return 0
  }
  const withUnit = raw.trim()
  if (withUnit.endsWith('px')) {
    return parseFloat(withUnit)
  } if (withUnit.endsWith('rem')) {
    return (
      parseFloat(withUnit)
      * parseFloat(window.getComputedStyle(document.documentElement).fontSize)
    )
  } if (withUnit.endsWith('vw')) {
    return (parseFloat(withUnit) * window.innerWidth) / 100
  }
  if (IS_DEV) {
    error(
      'Global',
      `You are using a not supported CSS unit in \`${raw}\`. Only \`px\` \`rem\` and \`vw\` are supported.`,
    )
  }
  return 0
}
